package org.ifdb.persistency.entity;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Query;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.ifdb.persistency.PMF;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class State {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key        id;

    @Persistent
    private String     name;

    @Persistent
    @Element(dependent = "true")
    private List<City> cities = new ArrayList<City>();

    public List<City> getCities() {
        return cities;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Key getId() {
        return id;
    }

    public boolean addCity(City state) {
        return cities.add(state);
    }

    public boolean removeCity(City state) {
        return cities.remove(state);
    }

    public City getCityByName(String name) {
        City city = null;
        for (City c : cities) {
            if (c.getName().equals(name)) {
                city = c;
            }
        }
        return city;
    }

    public static final boolean exists(String stateName){
        State s = new State();
        s.setName(stateName);
        return State.exists(s);
    }
    
    @SuppressWarnings("unchecked")
    public static final boolean exists(State state){
        boolean exists = false;
        Query query = null ;
        try { 
             query = PMF.get().getPersistenceManager().newQuery(State.class);     
             query.setFilter("name == stateName");      
             query.declareParameters("String stateName"); 
        } catch(Exception e){}
          try {         
              List<State> results = (List<State>) query.execute(state.getName());         
              if (results.iterator().hasNext()) {
                  for (State s : results) {
                      s.getId();
                      exists = true;
                      break;
                  }
              } else {             
                  exists = false;
              }     
          } finally {        
          
              query.closeAll();     
          }
        return exists;
        
    }

    
}
